package com.igeek.compus.backend.notice.controller;


import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageInfo;
import com.igeek.compus.backend.notice.entity.Notice;
import com.igeek.compus.backend.notice.service.NoticeService;
import com.igeek.compus.backend.system.Constants;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.aspectj.weaver.ast.Not;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Controller
@RequestMapping("notice")
public class NoticeController {

    @Autowired
    private NoticeService noticeService ;

    /**
     * 获得通知列表
     * @param notice
     * @return
     */
    @RequestMapping("list.do")
    @ResponseBody
    public Map list(Notice notice){
        Map<String,Object> result=new HashMap<>();

        try{
            // 业务代码，用户信息查询
            PageInfo<Notice> pageInfo = new PageInfo<>(noticeService.getNoticeListByPage(notice));

            result.put("data", pageInfo.getList());
            result.put("count", pageInfo.getTotal());

            result.put("code", 0);
            result.put("msg", "查询成功");
        }catch (Exception e) {
            e.printStackTrace();
            result.put("code", 1);
            result.put("msg", "系统异常");
        }

        return result;
    }

    @RequestMapping("deleteNoticeById.do")
    @ResponseBody
    public void deleteNoticeById(Notice notice) {
        System.out.println(notice);
        noticeService.deleteNoticeById(notice);
    }

    @RequestMapping("deleteNoticeList.do")
    @ResponseBody
    public Map<String, Object> deleteNoticeList(String noticeIds) {
        Map<String, Object> result = new HashMap<>();

        List<String> noticeIdList = Arrays.asList(noticeIds.substring(1, noticeIds.length() - 1).split(","));

        // 2.执行业务
        try {
            if (noticeService.deleteNoticeList(noticeIdList) > 0) {
                result.put(Constants.RETCODE, Constants.SUCCESS_CODE);
                result.put(Constants.RETMSG, Constants.SUCCESS_MSG);
            } else {
                result.put(Constants.RETCODE, Constants.ERROR_CODE);
                result.put(Constants.RETMSG, Constants.SUCCESS_MSG);
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.put(Constants.RETCODE, Constants.SUCCESS_CODE);
            result.put(Constants.RETMSG, Constants.ERROR_MSG);
        }

        // 3.返回结果
        return result;
    }

    @RequestMapping("addNotice.do")
    @ResponseBody
    public Map<String, Object> addNotice(Notice notice) {
        Map<String, Object> result = new HashMap<>();

        // 1.参数校验
        if(StrUtil.isEmpty(notice.getContent()) || StrUtil.isEmpty(notice.getTitle())
                || notice.getPublisher() == null ){
            result.put(Constants.RETCODE, Constants.ERROR_CODE);
            result.put(Constants.RETMSG, Constants.PARAM_ERROR_MSG);
            return  result;
        }

        // 2.执行业务
        try {
            if(noticeService.addNotice(notice) > 0) {
                result.put(Constants.RETCODE, Constants.SUCCESS_CODE);
                result.put(Constants.RETMSG, Constants.SUCCESS_MSG);
            }else {
                result.put(Constants.RETCODE, Constants.ERROR_CODE);
                result.put(Constants.RETMSG, Constants.SUCCESS_MSG);
            }
        }catch (Exception e) {
            e.printStackTrace();
            result.put(Constants.RETCODE, Constants.SUCCESS_CODE);
            result.put(Constants.RETMSG, Constants.ERROR_MSG);
        }

        // 3.返回结果
        return result;
    }

    @RequestMapping("toNoticeEdit.do")
    @ResponseBody
    public ModelAndView toNoticeEdit(Integer id) {

        Notice notice = noticeService.getNoticeInfoById(id);

        Map<String, Object> map = new HashMap<>();
        map.put("id",notice.getId());
        map.put("title", notice.getTitle());
        map.put("content", notice.getContent());
        map.put("publisher", notice.getPublisher());

        return new ModelAndView("/notice/notice_edit", map);
    }



    @RequestMapping("updateNotice.do")
    @ResponseBody
    public Map<String, Object> updateNotice(Notice notice) {
        Map<String, Object> result = new HashMap<>();

        // 1.参数校验
        if(notice.getId()==null) {
            result.put(Constants.RETCODE, Constants.ERROR_CODE);
            result.put(Constants.RETMSG, Constants.PARAM_ERROR_MSG);
            return  result;
        }

        // 2.执行业务
        try {
            if(noticeService.updateNotice(notice) > 0) {
                result.put(Constants.RETCODE, Constants.SUCCESS_CODE);
                result.put(Constants.RETMSG, Constants.SUCCESS_MSG);
            }else {
                result.put(Constants.RETCODE, Constants.ERROR_CODE);
                result.put(Constants.RETMSG, Constants.SUCCESS_MSG);
            }
        }catch (Exception e) {
            e.printStackTrace();
            result.put(Constants.RETCODE, Constants.SUCCESS_CODE);
            result.put(Constants.RETMSG, Constants.ERROR_MSG);
        }

        // 3.返回结果
        return result;
    }

    @RequestMapping("exportNoticeList.do")
    @ResponseBody
    public void export(Notice notice, HttpServletRequest request, HttpServletResponse response) throws Exception {

        OutputStream outputStream = null;

        try {

            List<Notice> noticeList = noticeService.getNoticeListByPage(notice);

            String fileName = "菜单报表.xls";
            String userAgent = request.getHeader("USER-AGENT").toLowerCase();
            String outputFileName = fileName;
            if (userAgent.toUpperCase().indexOf("MSIE") > 0) {
                outputFileName = URLEncoder.encode(fileName, "UTF-8");
            } else if (userAgent.toUpperCase().indexOf("IPHONE") > 0) {
                outputFileName = new String(fileName.getBytes(), "ISO-8859-1");
            } else {
                outputFileName = new String(fileName.getBytes("utf-8"), "ISO-8859-1");
            }
            String[] titles = {"主题", "通知内容", "发布者", "创建时间"};

            // 2.导出excel，需要标题栏，需要数据
            HSSFWorkbook wb = noticeService.noticeExport(titles, noticeList);

            response.setContentType("application/octet-stream");
            // 以附件的形式下载
            response.setHeader("Content-disposition", "attachment; filename=\"" + outputFileName + "\"");

            outputStream = response.getOutputStream();
            wb.write(outputStream);

            outputStream.flush();
            outputStream.close();

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @RequestMapping("upload.do")
    @ResponseBody
    public void upload(@RequestParam("multipartFile") MultipartFile multipartFile) throws Exception {
        // 获得文件类型
        String contentType = multipartFile.getContentType();
        System.out.println(contentType);
        if(contentType.contains("jpg") || contentType.contains("jpeg") || contentType.contains("png")) {
            // 获得文件名
            String fileName = "weixinpicture.jpeg";
            File file = new File("\\Users\\lenovo\\Desktop\\" + fileName);
            if(!file.exists() || file.isDirectory()) {
                file.mkdirs();
            }
            multipartFile.transferTo(file);
        }
    }
}
